<template>
	<view class="pages" :style="{minHeight:$height()}">
		<view class="tishi" v-show="xianzhi.show">成功签约售电合同,成为A类代理人可查看更多</view>
		<!-- <view class="suofangjjibie">
			方式：{{causedBy == 'drag' ? '拖拽' :'缩放'}}
			缩还是放：{{issuofang}}
			缩放级别：{{suofangjibie}}
			<u-button type="primary" :custom-style="{width:'60px'}" @click="sheng">省</u-button>
			<u-button type="primary" @click="shi" :custom-style="{width:'60px'}" >市</u-button>
			<u-button type="primary" @click="qu" :custom-style="{width:'60px'}" >区</u-button>
			<u-button type="primary" @click="jiedao" :custom-style="{width:'60px'}" >街道</u-button>
			<u-button type="primary" @click="ceshi" :custom-style="{width:'60px'}" >cecdsfdsfdsfdsfdsf</u-button>
		</view> -->
		<map style="width: 100%; height: 100vh;" :latitude="latitude" :longitude="longitude" :markers="markers"
			:scale="scale" @markertap="markertap" :max-scale="maxscale" :min-scale="minscale" :circles="circles"
			@regionchange="regionchange" enable-building="true" @callouttap="callouttap" id="mapId" ref="mapId"
			:getRegion="getRegion" :enable-zoom="xianzhi.enable_zoom" :enable-scroll="xianzhi.enable_scroll">
		</map>
		<CustomerPoolMapListCom ref="CustomerPoolMapListComRef" class="custersd"></CustomerPoolMapListCom>
		<u-popup v-model="hotshow" mode="bottom" style="position: relative;" height="450rpx" :mask-close-able="false">
			<view class="modelbox">
				<view class="modelbox_haders">
					客户信息
				</view>
				<view class="colse" @click="hotshow = false">
					<u-icon name="close"></u-icon>
				</view>
				<view class="modelbox_content_box">
					<view class="item">
						<view class="list">
							<view class="left">
								公司名称：
							</view>
							<view class="right">
								<view class="centent">
									{{hotData.companyName || ''}}
								</view>
							</view>
						</view>
						<view class="list">
							<view class="left">
								电话：
							</view>
							<view class="right">
								<view class="centent ipohe" @click="PhoneCall(hotData.mobile)">
									{{hotData.mobile || ''}}
								</view>
							</view>
						</view>
						<view class="list">
							<view class="left">
								绑定时间：
							</view>
							<view class="right">
								<view class="centent">
									{{$utils.formatTimeRange(hotData.bindTime) || ''}}
								</view>
							</view>
						</view>
						<view class="list col">
							<view class="left">
								地址：
							</view>
							<view class="right">
								<view class="centent">
									{{ hotData.province ? `${hotData.province},` : ''}}
									{{ hotData.area ? `${hotData.area},` : ''}}
									{{ hotData.district ? `${hotData.district},` : ''}}
									{{ hotData.usePowerAddress ? `${hotData.usePowerAddress}` : ''}}
								</view>
							</view>
						</view>
						<!-- 						<view class="list">
							<view class="left">
								范围：
							</view>
							<view class="right">
								<view class="centent" style="color: red;">
									{{item.lds || ""}}
								</view>  
							</view>
						</view> -->
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import CustomerPoolMapListCom from './CustomerPoolMapListCom'
	export default {
		components: {
			CustomerPoolMapListCom
		},
		data() {
			return {
				xianzhi: {
					show: true,
					enable_zoom:false,
					enable_scroll:false
				},
				// 定义缩放级别数组，这里假设对应全国、省、市的缩放级别
				currentScaleIndex: 0, // 当前缩放级别索引
				closest: null, //找最近的级别
				causedBy: null,
				issuofang: '',
				getRegion: null,
				hotshow: false,
				hotData: {},
				keywords: '',
				page: 1,
				limit: 10,
				more: false,
				suofangjibie: 14.8,
				// 页面数据初始化状态
				loadText: {
					loadmore: '轻轻上拉，加载更多',
					loading: '努力加载中',
					nomore: '我也是有底线的'
				},
				distance: 1.8461370658824359, //中心点到边界的距离(公里)
				lat: '',
				lng: '',
				type: 1,
				circles: [], //在地图上显示圆
				customList: [], //客户信息
				show: false,
				id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				latitude: 34.252109,
				longitude: 108.840866,
				markers: [], //所有标点数据源
				scale: 14.8, //缩放级别（省级别：6~8；市级别：9~15；区级别：16以上）
				linshiscale: 17.35, //随时的缩放比例
				maxscale: 20, //最大缩放级别到区
				minscale: 3, //最小缩放级别	,到省
				corporationDetalis: false, //是否要请求公司详情接口，并打开弹框
				centerLat: null,
				centerlng: null,
				stop: false,
			}
		},
		onLoad(options) {
			// this.getUser()
			this.latitude =Number(options.latitude) 
			this.longitude = Number(options.longitude)
			this.centerLat = this.latitude
			this.centerlng = this.longitude
			this.GetData(this.scale)
			var userInfo_level= uni.getStorageSync("userInfo_level")
			console.log(userInfo_level,"999999999999999999999")
			//非A级别代理 默认锁定地图
			if(userInfo_level==0){
				this.xianzhi.show=false
				this.xianzhi.enable_zoom=true
				this.xianzhi.enable_scroll=true
			}
		},
		onShow() {
			// this.change_markers()
			// this.getshengshiqu()
		},
		methods: {
			
			// getUser() {
			// 	this.$axios.request(this.$api.getUser, "GET").then((val) => {
			// 		this.userinfo = val.data
			// 	})
			// },
			change_markers() {
				this.circles = [{
					latitude: this.latitude,
					longitude: this.longitude,
					// iconPath: '/static/Icon/shoudianlogo.png',
					// fillColor: "#9db0de6A", //填充颜色
					// color: "#00aaff", //描边的颜色
					// radius: 10000, //半径
					// strokeWidth: 0, //描边的宽度
				}, ]
			},
			// 获取所有省市区在地图上的标记点
			getshengshiqu() {
				this.corporationDetalis = false
				var apiUrl = ''
				if (this.type == 1) {
					// 省份的接口
					apiUrl = this.$api.customerPoolMapcountProvince
				} else if (this.type == 2) {
					// 市的接口
					apiUrl = this.$api.customerPoolMapcountArea
				} else if (this.type == 3) {
					// 区的接口
					apiUrl = this.$api.customerPoolMapcountDistrict
				}
				let parms = {
					distance: this.distance,
					lat: this.centerLat,
					lng: this.centerlng
				}
				this.$axios.request(apiUrl, "GET", this.type != 1 ? parms : {}).then(res => {
					this.markers = res.data.map((item, index) => {
						var lat = Number(item.lat);
						var lng = Number(item.lng);
						if (this.type == 1) {
							// 省份的接口
							lat = Number(item.provinceLat);
							lng = Number(item.provinceLng);
						} else if (this.type == 2) {
							// 市的接口
							lat = Number(item.areaLat);
							lng = Number(item.areaLng);
						} else if (this.type == 3) {
							// 区的接口
							lat = Number(item.districtLat);
							lng = Number(item.districtLng);
						}
						return {
							id: index,
							latitude: lat, //纬度
							longitude: lng, //经度
							iconPath: '/static/Icon/shoudianlogo.png',
							width: 37,
							height: 37,
							callout: { //自定义标记点上方的气泡窗口 点击有效
								content: `${item.value}家`, //文本
								color: '#FFFFFF', //文字颜色
								fontSize: 15, //文本大小
								borderRadius: 5, //边框圆角
								bgColor: '#00aaff', //背景颜色
								display: 'ALWAYS', //常显
								padding: 2,
								latitude: lat, //纬度
								longitude: lng, //经度
								name: item.name
							},
						}
					})
				})
			},
			// 缩放到省
			sheng() {
				this.scale = 5
			},
			shi() {
				this.scale = 8
			},
			qu() {
				this.scale = 11
			},
			ceshi() {
				this.scale = 5
				this.latitude = 38.606917
				this.longitude = 76.75968
			},
			// 手机拨号
			PhoneCall(val) {
				if (val) {
					uni.makePhoneCall({
						phoneNumber: `${val}`
					})
				} else {}
			},
			// 点击标记点触发
			markertap(e) {
				console.log('点我试试看', e);
				this.showModel(e)
			},
			// 点击label触发
			callouttap(e) {
				this.showModel(e)
			},
			// 打开用户信息弹框
			showModel(e) {
				// 小程序
				// #ifdef MP-WEIXIN 
				// corporationDetalis 此变量如果为true就请获取公司详情接口并且打开弹框，否则打开标记点的
				if (this.corporationDetalis && e.markerId !== 8888888) {
					this.$axios.request(this.$api.corporationDetalis, "GET", {
						id: this.markers[e.markerId].callout.corporationID
					}).then(res => {
						console.log(res, '获取企业详情');
						this.hotData = {
							...res.data
						}
						this.hotshow = true
					})
				} else {
					var type = this.type
					if (e.markerId !== 8888888) {
						this.lat = this.markers[e.markerId].latitude
						this.lng = this.markers[e.markerId].longitude
					} else {
						this.lat = this.markers[0].latitude
						this.lng = this.markers[0].longitude
						type = 4
					}
					switch (type) {
						case 1:
							this.$refs.CustomerPoolMapListComRef.province = this.markers[e.markerId].callout.name
							this.$refs.CustomerPoolMapListComRef.type = type
							this.$refs.CustomerPoolMapListComRef.start()
							break;
						case 2:
							this.$refs.CustomerPoolMapListComRef.area = this.markers[e.markerId].callout.name
							this.$refs.CustomerPoolMapListComRef.type = type
							this.$refs.CustomerPoolMapListComRef.start()
							break;
						case 3:
							this.$refs.CustomerPoolMapListComRef.district = this.markers[e.markerId].callout.name
							this.$refs.CustomerPoolMapListComRef.type = type
							this.$refs.CustomerPoolMapListComRef.start()
							break;
						case 4:
							this.$refs.CustomerPoolMapListComRef.lat = this.markers[0].latitude
							this.$refs.CustomerPoolMapListComRef.lng = this.markers[0].longitude
							this.$refs.CustomerPoolMapListComRef.type = type
							this.$refs.CustomerPoolMapListComRef.distance = this.markers[0].distance
							this.$refs.CustomerPoolMapListComRef.start()
							break;
						default:
					}
				}
				// #endif 
				// 抖音 
				// #ifdef MP-TOUTIAO 
				// corporationDetalis 此变量如果为true就请获取公司详情接口并且打开弹框，否则打开标记点的
				if (this.corporationDetalis) {
					this.$axios.request(this.$api.corporationDetalis, "GET", {
						id: this.markers[e.markerId].callout.corporationID
					}).then(res => {
						console.log(res, '获取企业详情');
						this.hotData = {
							...res.data
						}
						this.hotshow = true
					})
				} else {
					this.lat = this.markers[e.markerId].latitude,
						this.lng = this.markers[e.markerId].longitude
					switch (this.type) {
						case 1:
							this.$refs.CustomerPoolMapListComRef.province = this.markers[e.markerId].callout.name
							this.$refs.CustomerPoolMapListComRef.type = this.type
							this.$refs.CustomerPoolMapListComRef.start()
							break;
						case 2:
							this.$refs.CustomerPoolMapListComRef.area = this.markers[e.markerId].callout.name
							this.$refs.CustomerPoolMapListComRef.type = this.type
							this.$refs.CustomerPoolMapListComRef.start()
							break;
						case 3:
							this.$refs.CustomerPoolMapListComRef.district = this.markers[e.markerId].callout.name
							this.$refs.CustomerPoolMapListComRef.type = this.type
							this.$refs.CustomerPoolMapListComRef.start()
							break;
						default:

					}
				}
				// #endif 
			},
			//获取中心点位置
			getCenterLatLong() {
				let mapObjs = uni.createMapContext('mapId', this) // 得到map实例对象
				var that = this
				mapObjs.getCenterLocation({
					success: res => {
						that.centerLat = res.latitude
						that.centerlng = res.longitude
					},
					fail: res => {},
					complete: res => {}
				})
				mapObjs.getRegion({
					success: (res) => {
						// 可视区域的坐标范围信息在 res 中
						const southwest = res.southwest; // 西南角坐标
						const northeast = res.northeast; // 东北角坐标

						// 计算地图中心点坐标
						const centerLatitude = (southwest.latitude + northeast.latitude) / 2;
						const centerLongitude = (southwest.longitude + northeast.longitude) / 2;

						// 计算地图中心点到地图边界的距离（半径）
						const radiusInMeters = that.haversineDistance(
							centerLatitude,
							centerLongitude,
							northeast.latitude,
							northeast.longitude
						);
						that.distance = radiusInMeters / 1000
						console.log('地图中心点到边界的距离（半径，公里）：', that.distance);
					},
					fail: (error) => {
						console.error('获取可视区域坐标范围失败：', error);
					}
				});
			},
			// 计算两个经纬度坐标之间的距离（使用Haversine公式）
			haversineDistance(lat1, lon1, lat2, lon2) {
				const earthRadius = 6371000; // 地球半径，单位：米
				const dLat = (lat2 - lat1) * (Math.PI / 180);
				const dLon = (lon2 - lon1) * (Math.PI / 180);
				const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					Math.cos(lat1 * (Math.PI / 180)) * Math.cos(lat2 * (Math.PI / 180)) *
					Math.sin(dLon / 2) * Math.sin(dLon / 2);
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				const distance = earthRadius * c;
				return distance;
			},
			// 拖拽地图，根据拖动不同级别，获取省市区的标点数据
			regionchange(e) {
				// if(this.stop){
				// 	return
				// }
				this.getCenterLatLong()
				this.suofangjibie = e.mp.detail.scale
				console.log(e, 'eeeeeeeeeeeeeeeeeeeeeeeeee');
				this.causedBy = e.causedBy
				// this.issuofang = JSON.stringify(e)
				if (e.type == "end") {
					if (e.mp.detail.scale) {
						this.GetData(e.mp.detail.scale)
					}
				}
			},
			GetData(scale) {
				if (scale <= 5.7) {
					this.type = 1
					this.getshengshiqu()
				} else if (scale > 5.7 && scale <= 8) {
					this.type = 2
					this.getshengshiqu()
				} else if (scale > 8 && scale <= 12) {
					this.type = 3
					this.getshengshiqu()
				} else if (scale > 12) {
					this.custoerListDetalis()
				}
			},
			custoerListDetalis() {
				this.corporationDetalis = true
				this.$axios.request(this.$api.custerManpHot, "GET", {
					lat: this.centerLat,
					lng: this.centerlng,
					limit: 200,
					page: 1,
					distance: this.distance
				}).then(res => {
					if (res.data.total > 200) {
						this.detailsMoreThen200(res.data.total)
						this.moreThen200DataList = res.data.list
						return
					}
					console.log("被停止了")
					this.stop = true
					this.markers = res.data.list.map((item, index) => {
						return {
							id: index,
							latitude: Number(item.lat), //纬度
							longitude: Number(item.lng), //经度
							iconPath: '/static/Icon/shoudianlogo.png',
							width: 37,
							height: 37,
							callout: { //自定义标记点上方的气泡窗口 点击有效
								content: `${item.companyName}`, //文本
								color: '#FFFFFF', //文字颜色
								fontSize: 15, //文本大小
								borderRadius: 5, //边框圆角
								bgColor: '#00aaff', //背景颜色
								display: 'ALWAYS', //常显
								padding: 2,
								latitude: Number(item.lat), //纬度
								longitude: Number(item.lng), //经度
								name: item.name,
								corporationID: item.id
							},
						}
					})
				})
			},
			detailsMoreThen200(count) {
				console.log("进入绘制了")
				var a = [{
					id: 8888888,
					latitude: this.centerLat, //纬度
					longitude: this.centerlng, //经度
					distance: this.distance,
					iconPath: '/static/Icon/shoudianlogo.png',
					width: 37,
					height: 37,
					callout: { //自定义标记点上方的气泡窗口 点击有效
						content: `${count}家`, //文本
						color: '#FFFFFF', //文字颜色
						fontSize: 15, //文本大小
						borderRadius: 5, //边框圆角
						bgColor: '#00aaff', //背景颜色
						display: 'ALWAYS', //常显
						padding: 2,
						latitude: this.centerLat, //纬度
						longitude: this.centerlng, //经度
						name: 'aaaaa'
					}
				}]
				console.log(a)
				this.markers = a
			}
		}
	}
</script>

<style scoped>
	.tishi {
		flex-direction: row;
		align-items: center;
		padding: 16rpx 30rpx;
		border-radius: 8rpx;
		position: relative;
		transition: all 0.3s linear;
		border: 1px solid #fff;
		background: red;
		font-weight: 900;
		color: white;
	}

	.pages {
		position: relative;
		width: 100%;
		height: 100vh;
		overflow-y: auto;
	}

	.custersd {
		/* 	position: fixed;
		left: 0;
		top: 20vh; */
	}

	.pagesbox {
		width: 750rpx;
		box-sizing: border-box;
		background-color: #fff;
	}

	.modelbox {

		width: 100%;
		height: calc(10vh - 100rpx);
		background-color: #fff;
		/* overflow-y: auto; */
		box-sizing: border-box;
	}

	.item {
		overflow: hidden;
		width: 100%;
		background-color: #fff;
		margin: 30rpx 0rpx;
		padding: 16rpx 32rpx;
		box-sizing: border-box;
	}

	.titleBox {
		display: flex;
		justify-content: space-between;
		align-items: center;
		/* width: 750rpx; */
		height: 42rpx;
		margin-top: 16rpx;
		margin: 0rpx 32rpx;
	}

	.txt {
		height: 40rpx;
		font-size: 32rpx;
		font-family: "PingFang SC";
		font-weight: 600;
		line-height: 40rpx;
		color: #333333;
	}

	.tag {
		/* width: 128rpx; */
		height: 40rpx;
		margin-left: 10rpx;
		font-size: 20rpx;
		font-family: "PingFang SC";
		font-weight: 400;
		line-height: 40rpx;
		color: #F5F5F5;
		/* text-align: center; */
		padding: 0 15rpx;
		background-color: #3975EA;
	}

	.biaoHao {
		height: 28rpx;
		font-size: 24rpx;
		font-family: "PingFang SC";
		font-weight: 400;
		line-height: 20rpx;
		color: #BBBBBB;
		margin: 15rpx 0 18rpx;
		margin-left: 32rpx;
	}

	.list {
		display: flex;
		border-bottom: 2px solid #f9f9f9;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		height: 60rpx;


	}

	.list:first-child {
		border-top: 2px solid #f9f9f9;
	}

	.left {
		width: 188rpx;
		height: 33rpx;
		font-size: 28rpx;
		font-family: "PingFang SC";
		font-weight: 600;
		line-height: 33rpx;
		color: #333333;
	}

	.right {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 590rpx;
		height: 33rpx;
	}

	.centent {
		font-size: 28rpx;
		font-family: "PingFang SC";
		font-weight: 300;
		color: #666;
	}

	.modelbox_haders {
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		line-height: 80rpx;
		height: 80rpx;
		font-size: 32rpx;
		font-family: "PingFang SC";
		font-weight: 700;
		/* background-color: #3975EA; */
	}

	.modelbox_content {
		width: 100%;
		/* height: calc(100% - 80rpx); */
		overflow-y: auto;
	}

	.modelbox_content_box {
		width: 100%;
		/* height: 100%; */
		overflow-y: auto;
	}

	.col {
		/* flex-direction: column; */
		/* align-items: flex-start; */
		height: 90rpx;
		padding: 6rpx 0;
		box-sizing: border-box;
	}

	.colse {
		position: absolute;
		top: -3rpx;
		right: 0rpx;
		width: 80rpx;
		height: 80rpx;
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;
		// background-color: #3975EA;
	}

	.ipohe {
		text-decoration: underline;
		color: #3975EA;
	}

	.suofangjjibie {
		position: fixed;
		top: 0;
		left: 0;
		width: 750rpx;
		height: 30rpx;
		z-index: 999;
		background-color: #fff;
		/* background-color: cornflowerblue;	 */
	}
</style>